<template>
  <div class="h-screen flex items-center">
    <div class="w-[800px]">
      <img class="w-full h-full" src="@/assets/image/login_left.png" alt="login" />
    </div>
    <div class="w-[450px] p-[50px] rounded-2xl shadow-2xl">
      <div class="flex justify-center mb-5 font-bold">江西携车通</div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" placeholder="请输入用户名">
            <template #prefix>
              <el-icon class="el-input__icon">
                <user />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password>
            <template #prefix>
              <el-icon class="el-input__icon">
                <lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div class="mb-2 text-[12px]">
        登录即表示同意江西携车通
        <span class="mx-2 text-[#409eff] cursor-pointer" @click="handleProtocolDetail(1)">平台服务协议</span>
        与<span class="ml-2 text-[#409eff] cursor-pointer" @click="handleProtocolDetail(2)">用户隐私政策</span>
      </div>
      <div class="buttonBox">
        <div>
          <el-button :icon="UserFilled" round size="large" type="primary" :loading="isLoading"
            @click="handleLogin(loginFormRef)">
            登录
          </el-button>
        </div>
        <div>
          <el-button :icon="CircleClose" round size="large" @click="handleResetForm(loginFormRef)">
            重置
          </el-button>
        </div>
        <div>
          <el-button :icon="DocumentAdd" round size="large" @click="register()">
            新企业备案
          </el-button>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="新企业备案" width="90%">
      <el-form :model="form" label-width="auto" :rules="rules">
        <div class="fromBox">
          <el-form-item label="企业名称" prop="companyName">
            <el-input v-model="form.companyName" />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditIdentifier">
            <el-input v-model="form.unifiedSocialCreditIdentifier" />
          </el-form-item>
          <el-form-item label="行政区划" prop="city">
            <el-input v-model="form.city" />
          </el-form-item>
          <el-form-item label="企业地址" prop="companyAddress">
            <el-input v-model="form.companyAddress" />
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="企业邮箱" prop="companyEmail">
            <el-input v-model="form.companyEmail" />
          </el-form-item>
          <el-form-item label="企业经济类型" prop="ecoType">
            <el-select v-model="form.ecoType" placeholder="请选择法人证件类型">
              <el-option value="国有经济" />
              <el-option value="集体经济" />
              <el-option value="私营经济" />
              <el-option value="个体经济" />
              <el-option value="联营经济" />
              <el-option value="股份制经济" />
              <el-option value="外商投资经济" />
              <el-option value="港澳台投资经济" />
              <el-option value="其他经济" />
            </el-select>
          </el-form-item>
          <el-form-item label="企业经营范围" prop="businessScope">
            <el-input v-model="form.businessScope" />
          </el-form-item>
          <el-form-item label="法人姓名" prop="legalName">
            <el-input v-model="form.legalName" />
          </el-form-item>
          <el-form-item label="法人证件类型" prop="legalType">
            <el-select v-model="form.legalType" placeholder="请选择法人证件类型">
              <el-option value="居民身份证" />
              <el-option value="临时身份证" />
              <el-option value="护照" />
              <el-option value="港澳同胞回乡证、港澳居民来往内地通行证" />
              <el-option value="中华人民共和国来往港澳通行证" />
              <el-option value="台湾居民来往大陆通行证" />
              <el-option value="大陆居民往来台湾通行证" />
            </el-select>
          </el-form-item>
          <el-form-item label="法人证件号" prop="legalNum">
            <el-input v-model="form.legalNum" />
          </el-form-item>
          <el-form-item label="法人电话" prop="legalPhone">
            <el-input v-model="form.legalPhone" />
          </el-form-item>
          <el-form-item label="负责人姓名" prop="principalName">
            <el-input v-model="form.principalName" />
          </el-form-item>
          <el-form-item label="负责人证件类型" prop="principalType">
            <el-select v-model="form.principalType" placeholder="请选择法人证件类型">
              <el-option value="居民身份证" />
              <el-option value="临时身份证" />
              <el-option value="护照" />
              <el-option value="港澳同胞回乡证、港澳居民来往内地通行证" />
              <el-option value="中华人民共和国来往港澳通行证" />
              <el-option value="台湾居民来往大陆通行证" />
              <el-option value="大陆居民往来台湾通行证" />
            </el-select>
          </el-form-item>
          <el-form-item label="负责人证件号码" prop="principalNum">
            <el-input v-model="form.principalNum" />
          </el-form-item>
          <el-form-item label="负责人电话" prop="principalPhone">
            <el-input v-model="form.principalPhone" />
          </el-form-item>
          <el-form-item label="新能源维修情况" prop="energySituation">
            <el-input v-model="form.energySituation" />
          </el-form-item>
          <el-form-item label="联系人姓名" prop="contactName">
            <el-input v-model="form.contactName" />
          </el-form-item>
          <el-form-item label="联系人电话" prop="contactPhone">
            <el-input v-model="form.contactPhone" />
          </el-form-item>
          <el-form-item label="发证机构" prop="licensorInstitution">
            <el-input v-model="form.licensorInstitution" />
          </el-form-item>
          <el-form-item label="企业经营状态" prop="runStatus">
            <el-select v-model="form.runStatus" placeholder="请选择法人证件类型">
              <el-option :value="1" label="存续" />
              <el-option :value="2" label="在业" />
              <el-option :value="3" label="吊销" />
              <el-option :value="4" label="注销" />
              <el-option :value="5" label="迁入" />
              <el-option :value="6" label="迁出" />
              <el-option :value="7" label="停业" />
              <el-option :value="8" label="清算" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否省内业务" prop="isProvincial">
            <el-select v-model="form.isProvincial" placeholder="请选择法人证件类型">
              <el-option value="是" />
              <el-option value="否" />
            </el-select>
          </el-form-item>
          <el-form-item label="企业经营业务类别" prop="businessType">
            <el-input v-model="form.businessType" />
          </el-form-item>
          <el-form-item label="维修企业类型" prop="repairType">
            <el-select v-model="form.repairType" placeholder="请选择维修企业类型" @change="formRepairTypeChange">
              <el-option label="一类维修企业" :value="1" />
              <el-option label="二类维修企业" :value="2" />
              <el-option label="三类维修企业" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="维修分类" prop="DetailedRepair">
            <el-select v-model="form.DetailedRepair" multiple
              :placeholder="!(typeof form.repairType == 'number' && 1 <= form.repairType && form.repairType <= 3) ? '请先选择维修企业类型' : '请选择维修分类'"
              :disabled="!(typeof form.repairType == 'number' && 1 <= form.repairType && form.repairType <= 3)">
              <el-option v-if="form.repairType == 1" value="中大型汽车维修" />
              <el-option v-if="form.repairType == 2" value="中大型汽车维修-重型普货" />
              <el-option v-if="form.repairType == 2" value="中大型汽车维修-客车" />
              <el-option v-if="form.repairType == 1 || form.repairType == 2" value="小车维修" />
              <el-option v-if="form.repairType == 3" value="综合小修" />
              <el-option v-if="form.repairType == 3" value="专项维修" />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="维修分类" prop="uploadList">
            <el-upload class="upload-demo uploadStyle"
              action="https://xct.gzwxxh.com/api/xiechetong/sysFile/media/upload" :on-change="handleChange"
              :file-list="form.uploadList">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addFirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, onBeforeUnmount, defineOptions } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { CircleClose, UserFilled, DocumentAdd } from "@element-plus/icons-vue";
import useUserStore from "@/stores/modules/user";
import { loginApi } from "@/api/user";
import { addDynamicRoutes } from "@/router/modules/addDynamicRouter";
import { insert } from '@/api/user'
defineOptions({
  name: "Login"
});
interface RuleForm {
  phone: string;
  password: string;
}
const router = useRouter();
const userStore = useUserStore();
const loginFormRef = ref<FormInstance>();
const loginForm = reactive({
  phone: "",
  password: ""
});
const isLoading = ref(false);

// 校验规则
const loginRules = reactive<FormRules<RuleForm>>({
  phone: [{ required: true, message: "请输入用户手机号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

// 协议
const handleProtocolDetail = (id: number) => {
  const routeData = router.resolve({
    path: "/protocol",
    query: {
      id
    }
  });
  window.open(routeData.href, "_blank");
};

// 重置
const handleResetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 登录
const handleLogin = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;
    isLoading.value = true;
    try {
      // 登录
      const res = await loginApi({
        phone: loginForm.phone,
        password: loginForm.password
      });
      if (res) {
        userStore.$patch((state) => {
          state.token = (res as any).token;
          state.userInfo = (res as any).user;
        });
        // 动态添加路由
        await addDynamicRoutes();
        // 跳转首页
        router.push("/home/index");
      }
    } finally {
      isLoading.value = false;
    }
  });
};

const handleEnterKey = () => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (isLoading.value) return;
      handleLogin(loginFormRef.value);
    }
  };
};

//备案
const dialogVisible = ref(false)
const form = ref({
  companyName: void 0,
  unifiedSocialCreditIdentifier: void 0,
  city: void 0,
  companyAddress: void 0,
  phone: void 0,
  companyEmail: void 0,
  ecoType: void 0,
  businessScope: void 0,
  legalPhone: void 0,
  legalName: void 0,
  legalNum: void 0,
  legalType: void 0,
  principalName: void 0,
  principalNum: void 0,
  principalType: void 0,
  principalPhone: void 0,
  energySituation: void 0,
  contactName: void 0,
  contactPhone: void 0,
  licensorInstitution: void 0,
  runStatus: void 0,
  isProvincial: void 0,
  businessType: void 0,

  repairType: void 0,//一类维修企业（1）、二类维修企业（2），三类维修企业（3）
  DetailedRepair: new Array(),//大型汽车维修，小车维修  (就用字符串)
  uploadList: new Array()//字符串,字符串，字符串
})
const rules = {
  companyName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  unifiedSocialCreditIdentifier: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: '请输入统一社会信用代码', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入行政区划', trigger: 'blur' }
  ],
  companyAddress: [
    { required: true, message: '请输入企业地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: '请输入电话号码', trigger: 'blur' }
  ],
  companyEmail: [
    { required: true, message: '请输入企业邮箱', trigger: 'blur' },
    { pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '请输入企业邮箱', trigger: 'blur' }
  ],
  ecoType: [
    { required: true, message: '请输入企业经济类型', trigger: 'blur' }
  ],
  businessScope: [
    { required: true, message: '请输入企业经营范围', trigger: 'blur' }
  ],
  legalPhone: [
    { required: true, message: '请输入法人电话', trigger: 'blur' },
    { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: '请输入法人电话', trigger: 'blur' }
  ],
  legalName: [
    { required: true, message: '请输入法人姓名', trigger: 'blur' }
  ],
  legalNum: [
    { required: true, message: '请输入法人证件号', trigger: 'blur' }
  ],
  legalType: [
    { required: true, message: '请输入法人证件类型', trigger: 'blur' }
  ],
  principalName: [
    { required: true, message: '请输入负责人姓名', trigger: 'blur' }
  ],
  principalNum: [
    { required: true, message: '请输入负责人证件号码', trigger: 'blur' }
  ],
  principalType: [
    { required: true, message: '请输入负责人证件类型', trigger: 'blur' }
  ],
  principalPhone: [
    { required: true, message: '请输入负责人电话', trigger: 'blur' },
    { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: '请输入负责人电话', trigger: 'blur' }
  ],
  energySituation: [
    { required: true, message: '请输入新能源维修情况', trigger: 'blur' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
    { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: '请输入联系人电话', trigger: 'blur' }
  ],
  licensorInstitution: [
    { required: true, message: '请输入发证机构', trigger: 'blur' }
  ],
  runStatus: [
    { required: true, message: '请输入企业经营状态', trigger: 'blur' }
  ],
  isProvincial: [
    { required: true, message: '请输入是否省内业务', trigger: 'blur' }
  ],
  businessType: [
    { required: true, message: '请输入企业经营业务类别', trigger: 'blur' }
  ],
  repairType: [
    { required: true, message: '请输入是否省内业务', trigger: 'blur' }
  ],
  DetailedRepair: [
    { required: true, message: '请输入是否省内业务', trigger: 'blur' }
  ]
}
const register = () => {
  dialogVisible.value = true
}
const addFirm = async () => {
  const data = {
    ...form.value,
    DetailedRepair: form.value.DetailedRepair.join(","),
    uploadList: form.value.uploadList.map(item => item.response.data[0].accessUrl).join(",")
  }
  insert(data).then(res => {
    ElMessage(res.data)
    dialogVisible.value = false
  })
}

const formRepairTypeChange = () => {
  form.value.DetailedRepair = new Array()
}

const handleChange = (file: any, fileList: any[]) => {
  form.value.uploadList = fileList
}

onMounted(() => {
  document.addEventListener("keydown", handleEnterKey);
});
onBeforeUnmount(() => {
  document.removeEventListener("keydown", handleEnterKey);
});
</script>
<style scoped>
:deep(.el-button) {
  width: 200px;
}

.buttonBox {
  width: 100%;
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
  grid-gap: 15px 10px;
}

.buttonBox button {
  width: 100%;
}

.buttonBox>div:first-child {
  grid-column: 1/3;
}

.fromBox {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-column-gap: 10px;
}

.uploadStyle {
  display: flex;
}
</style>
